import React, { useState, useEffect } from 'react'
import * as echarts from 'echarts';
import './css/Welcome.less'
import '../../css/public.less'
//import './utils/css/public.less'
import { CaretUpFilled, CaretDownFilled } from '@ant-design/icons';
import { DatePickerProps, DatePicker } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import moment from 'moment'
import { useNavigate } from 'react-router-dom'
import { getWelcome, getCartogram, getOrderCartogram, getTimesCartogram, getTimesOrder } from '../../../api/lf'

dayjs.extend(customParseFormat);



export default
  function Welcome() {
  const navigator = useNavigate()
  type EChartsOption = echarts.EChartsOption;
  const echartsRef: any = React.createRef()
  const echartsRef2: any = React.createRef()
  const { RangePicker } = DatePicker;
  const dateFormat = 'YYYY-MM-DD';
  const weekFormat = 'MM-DD';
  const monthFormat = 'YYYY-MM';

  /**手动输入以下格式将执行日期解析*/
  const dateFormatList = ['DD-MM-YYYY', 'DD-MM-YY', 'DD-MM-YYYY', 'DD-MM-YY'];

  const customFormat: DatePickerProps['format'] = (value) =>
    `custom format: ${value.format(dateFormat)}`;

  const customWeekStartEndFormat: DatePickerProps['format'] = (value) =>
    `${dayjs(value).startOf('week').format(weekFormat)} ~ ${dayjs(value)
      .endOf('week')
      .format(weekFormat)}`;

  const today = moment()//当天时间




  /* 订单统计数据 */
  const [orderM, setOrderM] = useState<number>()//本月订单总数
  const [orderW, setOrderW] = useState<string>()//本周订单总数
  const [toLastMonth, setToLastMonth] = useState<number>()//上月订单
  const [toLastWeek, setToLastWeek] = useState<number>()//上周订单

  /* 销售额统计数据 */
  const [orderM2, setOrderM2] = useState<number>()//本月订单总数
  const [orderW2, setOrderW2] = useState<string>()//本周订单总数
  const [toLastMonth2, setToLastMonth2] = useState<number>()//上月订单
  const [toLastWeek2, setToLastWeek2] = useState<number>()//上周订单


  /* 周数据 */
  const [weekDataX, setWeekDataX] = useState<string[]>([]) //x轴数据
  const [weekDataY, setWeekDataY] = useState<number[]>([])//y轴数据
  const [weekDataX2, setWeekDataX2] = useState<string[]>([]) //x轴数据
  const [weekDataY2, setWeekDataY2] = useState<number[]>([])//y轴数据
  /* 日数据 */
  const [dayDataX, setDayDataX] = useState(['1', '2', '3', '4', '5', '6', '7'])
  const [dayDataY, setDayDataY] = useState([42, 24, 10, 55, 78, 100, 120])
  /* 月数据 */
  const [isClick, setIsClick] = useState(false)

  const [topData, setTopData] = useState<systemInfo>()//顶部统计数据
  const [pendingData, setPendingData] = useState<paddingInfo>()//待处理统计数据
  const [shopOverviewData, setShopOverviewData] = useState<productInfo>()//商品总览统计数据
  const [userOverviewData, setUserOverviewData] = useState<userInfo>()//用户总览统计数据

  interface systemInfo {
    orderTotal: number,
    payMoney: number,
    payMoneyW: number,
    payMoneyY: number,
  }
  interface paddingInfo {
    noPayment: number,
    payment: number,
    pendingReturn: number,
    shipments: number,
    noShipments: number,
    noReplacement: number,

  }
  interface productInfo {
    goodsTotal: number,
    inventory: number,
    listed: number,
    noListed: number,
  }
  interface userInfo {
    newUser: number,
    newUserM: number,
    newUserY: number,
    vipTotal: number,
  }

  /* 获取除图以外的所有数据 */
  function getAllData() {
    getWelcome().then(res => {
      /* console.log('所有数据', res); */
      setTopData(res.data.systemHome)
      setPendingData(res.data.pending)
      setShopOverviewData(res.data.productView)
      setUserOverviewData(res.data.userView)
    }).catch(err => {
      console.log('请求失败', err);

    })
  }
  /* 获取订单图表数据 */
  function getCartogramData() {
    getCartogram({ time: '1' }).then(res => {
      console.log('订单统计数据', res.data);
      const arr = res.data.total.map((item) => {
        return item.orderNum
      })
      const arr2 = res.data.total.map((item) => {
        return item.time
      })
      console.log('订单统计数据Y', arr);
      console.log('订单统计数据X', arr2);
      setWeekDataY(arr)
      setWeekDataX(arr2)
      setOrderM(res.data.compare.orderM)
      setOrderW(res.data.compare.orderW)
      setToLastMonth(res.data.compare.toLastMonth)
      setToLastMonth(res.data.compare.toLastWeek)

    }).catch(err => {
      console.log('请求失败', err);

    })

  }
  /* 获取销售图表数据 */
  function getOrderData() {
    getOrderCartogram({ time: '2' }).then(res => {
      console.log('销售统计数据', res.data);
      const arr3 = res.data.nextTotal.map((item) => {
        return item.orderNum
      })
      const arr4 = res.data.nextTotal.map((item) => {
        return item.time
      })
      console.log('订单统计数据Y2', arr3);
      console.log('订单统计数据X2', arr4);
      setWeekDataY2(arr3)
      setWeekDataX2(arr4)
      setOrderM2(res.data.nextCompare.orderM)
      setOrderW2(res.data.nextCompare.orderW)
      setToLastMonth2(res.data.nextCompare.toLastMonth)
      setToLastMonth2(res.data.nextCompare.toLastWeek)

    }).catch(err => {
      console.log('请求失败', err);

    })

  }



  useEffect(() => {
    getAllData()
    getCartogramData()
    getOrderData()
  }, [])

  useEffect(() => {
    console.log('订单统计数据Y888', weekDataY);

    //统计图
    const myChart = echarts.init(echartsRef.current);
    const myChart2 = echarts.init(echartsRef2.current);
    var option: EChartsOption;
    var option2: EChartsOption;

    option = {
      //折线图名字
      title: {
        text: "近一周订单统计",
        textStyle: {
          fontSize: 12,
          color: '#999999',
          fontWeight: 'lighter',

        }
      },
      backgroundColor: ' #ffffff',
      tooltip: {//提示框组件
        trigger: 'axis', //item数据项图形触发，主要在散点图，饼图等无类目轴的图表中使用。
        axisPointer: {
          // 坐标轴指示器，坐标轴触发有效
          type: 'line',// 默认为直线，可选为：'line' | 'shadow'
          lineStyle: {
            type: 'solid'
          }
        },
        /*  formatter: `${'2018-01-05 12:40'}<br/>订单量 :${164}` */
        /* formatter: function (params) {

          return params[0].axisValue + '<br/>' + '订单量:' + params[0].value

        } */
        formatter: '{b0}<br />订单量： {c0}'
      },
      xAxis: {
        type: 'category',
        data: weekDataX,
        boundaryGap: false,
        axisLine: {
          show: true,
          lineStyle: {
            width: 1,
            type: "solid"
          }
        }

      },

      yAxis: {
        type: 'value',
        scale: true,
        axisLine: {
          show: true,
          lineStyle: {
            width: 1,
            type: "solid"
          }
        },
        splitLine: {//去除网格线
          show: false
        },
        splitArea: { show: false }//去除网格区域
      },
      series: [
        {

          data: weekDataY,
          type: 'line',
          lineStyle: {
            color: '#3399ff'
          },
          areaStyle: {
            color: '#33ccff'
          },

        }
      ]

    };
    option2 = {
      //折线图名字
      title: {
        text: "近一周销售额统计",
        textStyle: {
          fontSize: 12,
          color: '#999999',
          fontWeight: 'lighter',

        }
      },
      backgroundColor: ' #ffffff',
      tooltip: {//提示框组件
        trigger: 'axis', //item数据项图形触发，主要在散点图，饼图等无类目轴的图表中使用。
        axisPointer: {
          // 坐标轴指示器，坐标轴触发有效
          type: 'line',// 默认为直线，可选为：'line' | 'shadow'
          lineStyle: {
            type: 'solid'
          }
        },
        /*  formatter: `${'2018-01-05 12:40'}<br/>订单量 :${164}` */
        /* formatter: function (params) {

          return params[0].axisValue + '<br/>' + '订单量:' + params[0].value

        } */
        formatter: '{b0}<br />销售额： {c0}'
      },
      xAxis: {
        type: 'category',
        data: weekDataX2,
        boundaryGap: false,
        axisLine: {
          show: true,
          lineStyle: {
            width: 1,
            type: "solid"
          }
        }

      },

      yAxis: {
        type: 'value',
        scale: true,
        axisLine: {
          show: true,
          lineStyle: {
            width: 1,
            type: "solid"
          }
        },
        splitLine: {//去除网格线
          show: false
        },
        splitArea: { show: false }//去除网格区域
      },
      series: [
        {

          data: weekDataY2,
          type: 'line',
          lineStyle: {
            color: '#3399ff'
          },
          areaStyle: {
            color: '#33ccff'
          },

        }
      ]

    };
    myChart.setOption(option);
    myChart2.setOption(option2);


  }, [weekDataY, weekDataY2])

  /* 给li绑定点击事件 */
  document.getElementById('ul')?.addEventListener('click', (e) => {
    console.log('被点击了');
    getCartogramData()
  })
  /*  */
  document.getElementById('ul2')?.addEventListener('click', (e) => {
    console.log('被点击了');
    getOrderData()
  })

  /* 时间选择框发生改变 */
  const onChangeDate = (dates: any, dateStrings: any) => {
    console.log('发请求');
    console.log('****', dateStrings);
    getTimesCartogram({ startTime: dateStrings[0], endTime: dateStrings[1] }).then(res => {
      console.log('指定时间段订单数据', res);
      const arr = res.data.total.map((item) => {
        return item.orderNum
      })
      const arr2 = res.data.total.map((item) => {
        return item.time
      })
      console.log('订单统计数据Y', arr);
      console.log('订单统计数据X', arr2);
      setWeekDataY(arr)
      setWeekDataX(arr2)
      setOrderM(res.data.compare.orderM)
      setOrderW(res.data.compare.orderW)
      setToLastMonth(res.data.compare.toLastMonth)
      setToLastMonth(res.data.compare.toLastWeek)
    }).catch(err => {
      console.log('err', err);

    })
  }
  /* 时间选择框2发生改变 */
  const onChangeDate2 = (dates: any, dateStrings: any) => {
    console.log('发请求');
    console.log('****', dateStrings);
    getTimesOrder({ startTime: dateStrings[0], endTime: dateStrings[1] }).then(res => {
      console.log('指定时间段销售额数据', res);
      const arr3 = res.data.nextTotal.map((item) => {
        return item.orderNum
      })
      const arr4 = res.data.nextTotal.map((item) => {
        return item.time
      })
      console.log('订单统计数据Y2', arr3);
      console.log('订单统计数据X2', arr4);
      setWeekDataY2(arr3)
      setWeekDataX2(arr4)
      setOrderM2(res.data.nextCompare.orderM)
      setOrderW2(res.data.nextCompare.orderW)
      setToLastMonth2(res.data.nextCompare.toLastMonth)
      setToLastMonth2(res.data.nextCompare.toLastWeek)

    }).catch(err => {
      console.log('err', err);

    })
  }
  /* 运营快捷入口 跳转 */
  const toGoodAdd = () => {
    navigator('/home/goods/GoodAdd')
  }
  const toOrderList = () => {
    navigator('/home/order/orderList')
  }
  const toUserList = () => {
    navigator('/home/user/userlist')
  }
  const toPromotionma = () => {
    navigator('/home/promotion/promotionma')
  }
  const toOperationSlide = () => {
    navigator('/home/operations/operationSlide')
  }

  return (
    <div className='Welcome' >
      {/* 头部 */}
      <div className='page-top'>
        {/* 左边标题 */}
        <div className='page-title'>
          <p>系统首页</p>
        </div>
      </div>
      {/* 销售情况统计 */}
      <div className='situation'>
        <div className='card'>
          <img src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" alt="" />
          <div>
            <span>今日订单总数</span>
            <p> {topData?.orderTotal} </p>
          </div>
        </div>
        <div className='card'>
          <img src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" alt="" />
          <div>
            <span>今日销售总额</span>
            <p> {topData?.payMoney} </p>
          </div>
        </div>
        <div className='card'>
          <img src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" alt="" />
          <div>
            <span>昨日销售总额</span>
            <p> {topData?.payMoneyY} </p>
          </div>
        </div>
        <div className='card'>
          <img src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" alt="" />
          <div>
            <span>近7天销售总额</span>
            <p> {topData?.payMoneyW} </p>
          </div>
        </div>



      </div>
      {/* 待处理事务 */}
      <div className='pending'>
        <div style={{ backgroundColor: '#f2f2f2', height: 40, lineHeight: "40px", }}><p style={{ marginLeft: "20px" }}>待处理事务</p></div>
        <div className='classification'>
          <div>
            <p>待付款订单</p>
            <span > ({pendingData?.noPayment}) </span>
          </div>
          <div>
            <p>已完成订单</p>
            <span > ({pendingData?.payment}) </span>
          </div>
          <div>
            <p>待确认退货订单</p>
            <span > ({pendingData?.pendingReturn}) </span>
          </div>
        </div>
        <div className='classification'>
          <div>
            <p>待发货订单</p>
            <span > ({pendingData?.noShipments}) </span>
          </div>
          <div>
            <p>已发货订单</p>
            <span > ({pendingData?.shipments}) </span>
          </div>
          <div>
            <p>待处理换货订单</p>
            <span > ({pendingData?.noReplacement}) </span>
          </div>
        </div>
      </div>
      {/* 运营快捷入口 */}
      <div className='fastEnter'>
        <div style={{ backgroundColor: '#f2f2f2', height: 40, lineHeight: "40px", }}><p style={{ marginLeft: "20px" }}>运营快捷入口</p></div>
        <div className='enter'>
          <div onClick={toGoodAdd}>
            <img src="https://img.axureshop.com/fe/ab/5b/feab5b871af043eba92a2fccffbfed0b/images/%E7%B3%BB%E7%BB%9F%E9%A6%96%E9%A1%B5%E6%95%B0%E6%8D%AE%EF%BC%88%E8%BE%85%E5%8A%A9%EF%BC%89/u4707.svg" alt="" />
            <p>添加商品</p>
          </div>
          <div onClick={toOrderList}>
            <img src="https://img.axureshop.com/fe/ab/5b/feab5b871af043eba92a2fccffbfed0b/images/%E7%B3%BB%E7%BB%9F%E9%A6%96%E9%A1%B5%E6%95%B0%E6%8D%AE%EF%BC%88%E8%BE%85%E5%8A%A9%EF%BC%89/u4707.svg" alt="" />
            <p>订单列表</p>
          </div>
          <div onClick={toUserList}>
            <img src="https://img.axureshop.com/fe/ab/5b/feab5b871af043eba92a2fccffbfed0b/images/%E7%B3%BB%E7%BB%9F%E9%A6%96%E9%A1%B5%E6%95%B0%E6%8D%AE%EF%BC%88%E8%BE%85%E5%8A%A9%EF%BC%89/u4707.svg" alt="" />
            <p>用户管理</p>
          </div>
          <div onClick={toPromotionma}>
            <img src="https://img.axureshop.com/fe/ab/5b/feab5b871af043eba92a2fccffbfed0b/images/%E7%B3%BB%E7%BB%9F%E9%A6%96%E9%A1%B5%E6%95%B0%E6%8D%AE%EF%BC%88%E8%BE%85%E5%8A%A9%EF%BC%89/u4707.svg" alt="" />
            <p>促销管理</p>
          </div>
          <div onClick={toOperationSlide}>
            <img src="https://img.axureshop.com/fe/ab/5b/feab5b871af043eba92a2fccffbfed0b/images/%E7%B3%BB%E7%BB%9F%E9%A6%96%E9%A1%B5%E6%95%B0%E6%8D%AE%EF%BC%88%E8%BE%85%E5%8A%A9%EF%BC%89/u4707.svg" alt="" />
            <p>轮播管理</p>
          </div>

        </div>
      </div>
      {/* 总览 */}
      <div className='overview'>
        <div className='overview-left'>
          <span style={{ height: 40, lineHeight: "40px", }}><p style={{ backgroundColor: '#f2f2f2', paddingLeft: "20px" }}>商品总览</p></span>
          <div>
            <ul>
              <li>{shopOverviewData?.listed}</li>
              <p>已上架</p>
            </ul>
            <ul>
              <li>{shopOverviewData?.noListed}</li>
              <p>已下架</p>
            </ul>
            <ul>
              <li>{shopOverviewData?.inventory}</li>
              <p>库存紧张</p>
            </ul>
            <ul>
              <li>{shopOverviewData?.goodsTotal}</li>
              <p>全部商品</p>
            </ul>

          </div>


        </div>
        <div className='overview-right'>
          <span style={{ height: 40, lineHeight: "40px", }}><p style={{ backgroundColor: '#f2f2f2', paddingLeft: "20px" }}>用户总览</p></span>
          <div>
            <ul>
              <li>{userOverviewData?.newUser}</li>
              <p>新增用户</p>
            </ul>
            <ul>
              <li>{userOverviewData?.newUserY}</li>
              <p>昨日新增</p>
            </ul>
            <ul>
              <li>{userOverviewData?.newUserM}</li>
              <p>本月新增</p>
            </ul>
            <ul>
              <li>{userOverviewData?.vipTotal}</li>
              <p>会员总数</p>
            </ul>

          </div>


        </div>

      </div>
      { /* 订单统计图 */}
      <div style={{ width: '95%', height: 407, marginTop: "40px" }}>
        {/* 统计图名 */}
        <div style={{ backgroundColor: '#f2f2f2', height: 40, lineHeight: "40px", }}><p style={{ marginLeft: "20px" }}>订单统计</p></div>
        {/*统计图内容 */}
        <div className='content-box' >
          <div className='content-left'>
            <div>
              <span>本月订单总数</span>
              <p>{orderM}</p>
              <span>
                <CaretUpFilled style={{ fontSize: '16px', color: "#33ccff", }} />

                <span style={{ color: '#33ccff' }}>10%</span><span>同比上月</span></span>
            </div>
            <div>
              <span>本周单总数</span>
              <p>{orderW}</p>
              <span><CaretDownFilled style={{ fontSize: '16px', color: "#ff0000" }} /><span style={{ color: '#ff0000' }}>10%</span><span>同比上周</span></span>
            </div>

          </div>
          <div className='content-right'>
            <div className='content-right-top'>
              <ul id='ul'>

                <li>
                  本周
                </li>

              </ul>
              <RangePicker onChange={onChangeDate} style={{ width: '195px', height: '27px' }}
                /*  defaultValue={moment(today)} */
                format={dateFormat}
              />

            </div>


            <div ref={echartsRef} style={{
              width: '100%',
              height: '90%',
            }}>
            </div>

          </div>
        </div>

      </div>
      {/* 销售额统计图 */}
      <div style={{ width: '95%', height: 407, marginTop: "40px" }}>
        {/* 统计图名 */}
        <div style={{ backgroundColor: '#f2f2f2', height: 40, lineHeight: "40px", }}><p style={{ marginLeft: "20px" }}>销售额统计图</p></div>
        {/*统计图内容 */}
        <div className='content-box' >
          <div className='content-left'>
            <div>
              <span>本月销售额</span>
              <p>{orderM2}</p>
              <span><CaretUpFilled style={{ fontSize: '16px', color: "#33ccff" }} />


                <span style={{ color: '#33ccff' }}>10%</span><span>同比上月</span></span>
            </div>
            <div>
              <span>本周销售额</span>
              <p>{orderW2}</p>
              <span><CaretDownFilled style={{ fontSize: '16px', color: "#ff0000" }} /><span style={{ color: '#ff0000' }}>10%</span><span>同比上周</span></span>
            </div>

          </div>
          <div className='content-right'>
            <div className='content-right-top'>
              <ul id='ul2' >

                <li >
                  本周
                </li>

              </ul>
              <RangePicker onChange={onChangeDate2} style={{ width: '20%', height: '27px' }}
                /*  defaultValue={moment(today)} */
                format={dateFormat}
              />

            </div>




            <div ref={echartsRef2} style={{
              width: '100%',
              height: '90%',
            }}>
            </div>

          </div>
        </div>


      </div>

    </div>

  )
}

